package com.project.api.ym.dao;



import com.alibaba.fastjson.JSONArray;
import com.project.api.common.ApiResponse;
import com.project.api.ym.model.Activity;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

@Repository
public class ActivityDao {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    @Qualifier("mainJdbcTemplate")
    private JdbcTemplate mainJdbcTemplate;

    @Autowired
    private AdminDao adminDao;

    @Autowired
    private ActivityAttachDao activityAttachDao;
    public long ActivityCreate(JSONObject json, long creator, long updateby) throws Exception {
        String sql="insert into "+ Activity.tableName +"(creator,updateby,title,introduction,address,atype,price,images,stime,etime,ctime,utime,gtime,otime,`status`,is_msg,is_send,is_material,is_hot,area,lot,lat,link,pws) " +
                "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        long id=0;
//        try {
            KeyHolder keyHolder = new GeneratedKeyHolder();
            mainJdbcTemplate.update(new PreparedStatementCreator() {
                @Override
                public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                    PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
                    ps.setLong(1,creator);
                    ps.setLong(2,updateby);
                    String title = (String) json.getOrDefault("title",null);
                    if (title == null) ps.setNull(3, Types.NULL);else ps.setString(3, title);
                    String introduction = (String) json.getOrDefault("introduction",null);
                    if (introduction==null) ps.setNull(4,Types.NULL);else ps.setString(4,introduction);
                    String address = (String)json.getOrDefault("address",null);
                    if (address==null) ps.setNull(5,Types.NULL);else ps.setString(5,address);
                    ps.setInt(6, (Integer) json.getOrDefault("atype",0));
                    Object priceStr=json.getOrDefault("price","0");
                    double price=Double.valueOf(String.valueOf(priceStr));
                    ps.setDouble(7, price);
//                    ArrayList<String> images= (ArrayList<String>) json.getOrDefault("images",new ArrayList<>());
                    List images= (ArrayList<String>) json.getOrDefault("images",new ArrayList<>());
                    JSONArray jsonArray=new JSONArray(images);
                    String imgStr=jsonArray.toString();
//                    String imgStr = String.join(",",images);
//                    String[] imgs = images.toArray(new String[images.size()]);
//                    String imgStr= Arrays.toString(imgs);
                    ps.setString(8,imgStr);
                    ps.setLong(9, (Long) json.getOrDefault("stime",0L));
                    ps.setLong(10, (Long) json.getOrDefault("etime",0L));
                    ps.setLong(11, (Long) json.getOrDefault("ctime",System.currentTimeMillis()));
                    ps.setLong(12, (Long) json.getOrDefault("utime",System.currentTimeMillis()));
                    ps.setLong(13, (Long) json.getOrDefault("gtime",System.currentTimeMillis()));
                    ps.setLong(14, (Long) json.getOrDefault("otime",System.currentTimeMillis()));
                    ps.setInt(15, (Integer) json.getOrDefault("status",0));
                    ps.setInt(16, (Integer) json.getOrDefault("is_msg",0));
                    ps.setInt(17, (Integer) json.getOrDefault("is_send",0));
                    ps.setInt(18, (Integer) json.getOrDefault("is_material",0));
                    ps.setInt(19, (Integer) json.getOrDefault("is_hot",0));
                    String area = (String) json.getOrDefault("area",null);
                    if (area == null) ps.setNull(20, Types.NULL);else ps.setString(20, area);
                    String lot = (String) json.getOrDefault("lot",null);
                    if (lot == null) ps.setNull(21, Types.NULL);else ps.setString(21, lot);
                    String lat = (String) json.getOrDefault("lat",null);
                    if (lat == null) ps.setNull(22, Types.NULL);else ps.setString(22, lat);
                    String link = (String) json.getOrDefault("link",null);
                    if (link == null) ps.setNull(23, Types.NULL);else ps.setString(23, link);
                    String pws = (String) json.getOrDefault("pws",null);
                    if (pws == null) ps.setNull(24, Types.NULL);else ps.setString(24, pws);
                    return ps;
                }
            }, keyHolder);
            id=keyHolder.getKey().intValue();
//        } catch (Exception  e) {
//            logger.error(e.getMessage());
//            throw new Exception(e.getMessage());
//        }
        return id;
    }

    public long ActivityUpdate(long activity_id,long updateby,JSONObject json){
        String sql="update "+Activity.tableName+" set updateby= ? ,title=? , introduction=? , address=? , atype=? , price=? , " +
                "images=? , stime=? , etime=? , utime=? ,gtime=? , otime=? , `status`=? , is_msg=? , is_send=? , is_material=? , is_hot=? , area=? , lot=? , lat=? , link=? , pws=?  " +
                " where id = ?";
        String t = (String) json.getOrDefault("title",null);
        Object title = (String) json.getOrDefault("title",null)==null?Types.NULL:t;
        String i = (String) json.getOrDefault("introduction",null);
        Object introduction = (String) json.getOrDefault("introduction",null)==null?Types.NULL:i;
        String a = (String)json.getOrDefault("address",null);
        Object address = (String) json.getOrDefault("address",null)==null?Types.NULL:a;
        int atype=(Integer) json.getOrDefault("atype",0);
        Object priceStr= json.getOrDefault("price","0");
        double price=Double.valueOf(String.valueOf(priceStr));
        List images= (ArrayList<String>) json.getOrDefault("images",new ArrayList<>());
        JSONArray jsonArray=new JSONArray(images);
        String imgStr=jsonArray.toString();
//        String imgStr = String.join(",",images);
//        String[] imgs = images.toArray(new String[images.size()]);
//        String imgStr=Arrays.toString(imgs);
        long stime=Long.valueOf(String.valueOf( json.getOrDefault("stime","0")));
        long etime=Long.valueOf(String.valueOf(json.getOrDefault("etime","0")));
        long gtime=Long.valueOf(String.valueOf(json.getOrDefault("gtime","0")));
        long otime=Long.valueOf(String.valueOf(json.getOrDefault("otime","0")));
        int status=(Integer) json.getOrDefault("status",0);
        int is_msg=(Integer) json.getOrDefault("is_msg",0);
        int is_send=(Integer) json.getOrDefault("is_send",0);
        int is_material=(Integer) json.getOrDefault("is_material",0);
        int is_hot=(Integer) json.getOrDefault("is_hot",0);
        String ar = (String) json.getOrDefault("area",null);
        Object area = ar==null?Types.NULL:ar;
        String ot = (String) json.getOrDefault("lot",null);
        Object lot = ot==null?Types.NULL:ot;
        String at = (String) json.getOrDefault("lat",null);
        Object lat = ot==null?Types.NULL:at;
        String li = (String) json.getOrDefault("link",null);
        Object link = li==null?Types.NULL:li;
        String pw = (String) json.getOrDefault("pws",null);
        Object pws = pw==null?Types.NULL:pw;
        int res=mainJdbcTemplate.update(sql, updateby,title,introduction,address,atype,price,imgStr,stime,etime,System.currentTimeMillis(),gtime,otime,status,is_msg,is_send,is_material,is_hot,area,lot,lat,link,pws,activity_id);
        return activity_id;
    }

    public boolean ActivityDelete(ArrayList<String> ids){
        String i="("+String.join(",", ids)+")";
        String sql="delete from "+Activity.tableName+" where id in"+i;
        int res=mainJdbcTemplate.update(sql);
        return true;
    }

    public Activity GetActivityById(long id){
        Activity res=new Activity();
        String sql = "SELECT * FROM "+ Activity.tableName +" where `id`=?";
        try {
            res = (Activity) mainJdbcTemplate.queryForObject(
                    sql, new Object[] {id},new BeanPropertyRowMapper(Activity.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return res;
        }
        if (res!=null){
            res.setAttach(activityAttachDao.GetActivityAttach(id));
            res.setCreate_admin(adminDao.GetAdminById(res.getCreator()));
            res.setUpdate_admin(adminDao.GetAdminById(res.getUpdateby()));
        }
        return res;
    }

    public int GetActivityCount(String condition){
        String sql = "select count(*) from "+Activity.tableName;
        if (condition!=null && !condition.equalsIgnoreCase("")){
            sql=sql+" where 1=1 "+condition;
        }
        int count = mainJdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }

    public List<Activity> GetActivity(String condition){
        List<Activity> res = new ArrayList<>();
        String sql = "SELECT * FROM "+ Activity.tableName ;
        if (condition!=null && !condition.equalsIgnoreCase("")){
            sql=sql+" where 1=1 "+condition;
        }
        try {
            res = mainJdbcTemplate.query(
                    sql, new Object[] {},new BeanPropertyRowMapper(Activity.class));
        } catch (EmptyResultDataAccessException e) {//捕获查询不到
            return res;
        }
        Iterator<Activity> iter = res.iterator();
        while (iter.hasNext()) {
            Activity r =  iter.next();
            r.setAttach(activityAttachDao.GetActivityAttach(r.getId()));
            r.setCreate_admin(adminDao.GetAdminById(r.getCreator()));
            r.setUpdate_admin(adminDao.GetAdminById(r.getUpdateby()));
        }
        return res;
    }

    public boolean UpdateStatus(long id,int status){
        String sql= "update "+Activity.tableName+" set status="+status +", utime="+System.currentTimeMillis()+" where id ="+id;
        int res=mainJdbcTemplate.update(sql);
        return true;
    }

    public boolean UpdateSend(long id, int send){
        String sql= "update "+Activity.tableName+" set is_msg=1, is_send="+send +", utime="+System.currentTimeMillis()+" where id ="+id;
        int res=mainJdbcTemplate.update(sql);
        return true;
    }
}
